<?php
/* 
 *出库管理 销售
 */
class SaleAction extends TransAction {
    public function _filter(&$map) {
        //archive search or export order for the archive data
        if(strpos(__ACTION__,'/archive') !== false || strpos(__SELF__,'=archive') !== false)
            $archive_suffix = "_archive"; 
        else
            $archive_suffix = "";
        
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
             $map['_complex'] = A('Search')->search($key,'Sale_detail'.$archive_suffix,'sale_title','Sale_detail'.$archive_suffix.'.id');
           //$where['Sale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
               // $where['Sale.customer_name'] = array('like',"%".$key."%");//产品名称
               // $where['Sale.shipping_name'] = array('like',"%".$key."%"); 
               // $where['Sale.logino'] = array('like',"%".$key."%");
               // $where['Sale.address'] = array('like',"%".$key."%");
               // $where['Sale.mobile'] = array('like',"%".$key."%");
               // $where['Sale.phone'] = array('like',"%".$key."%");
               // $where['Sale.remark'] = array('like',"%".$key."%");
           /* 
            $where['_logic'] = "or";
            $map['_complex'] = $where;*/
        }
        $pname = trim($_REQUEST['product_name']); //系统内部货品名称搜索
        if(!empty($pname))
             $map['_complex'] = A('Search')->search($pname,'Product','name','Product.id');

        if(!empty($_REQUEST['order_no'])) {
            $key2 = trim($_REQUEST['order_no']);
            if(!empty($_REQUEST['product_name']) ||!empty($_REQUEST['keywords']) || ($_REQUEST['etype'] == 'detail') )
              $map['_string'] = '(Sale'.$archive_suffix.'.sale_no = "'.$key2.'")  OR ( Sale'.$archive_suffix.'.mall_no like "%'.$key2.'%") ';
            else
              $map['_string'] = '(sale_no = "'.$key2.'")  OR ( mall_no like "%'.$key2.'%") ';
        }
       //模糊订单号搜索
        if(!empty($_REQUEST['like_order_no'])) {
            $key3 = trim($_REQUEST['like_order_no']);
            if(!empty($_REQUEST['product_name']) ||!empty($_REQUEST['keywords']) || ($_REQUEST['etype'] == 'detail') )
              $map['_string'] = '(Sale'.$archive_suffix.'.sale_no like "%'.$key3.'%")  OR ( Sale'.$archive_suffix.'.mall_no like "%'.$key3.'%") ';
            else
              $map['_string'] = '(sale_no like "%'.$key3.'%")  OR ( mall_no like "%'.$key3.'%") ';
        }

        if( $_REQUEST['remark'] != '' )
          $map['remark'] = trim($_REQUEST['remark']);

        if( $_REQUEST['logino'] != '' )
          $map['logino'] = array('eq',trim($_REQUEST['logino']));

        if( $_REQUEST['warehouse_id'] != '' )
            $map['warehouse_id'] = $_REQUEST['warehouse_id'];

        if( $_REQUEST['phone'] != '' )
          $map['phone'] = array('like',"%".trim($_REQUEST['phone'])."%");

        if( $_REQUEST['mobile'] != '' )
          $map['mobile'] = array('like',"%".trim($_REQUEST['mobile'])."%");

        if( $_REQUEST['address'] != '' )
          $map['address'] = array('like',"%".trim($_REQUEST['address'])."%");

        if( $_REQUEST['shipping_name'] != '' )
          $map['shipping_name'] = array('like',"%".trim($_REQUEST['shipping_name'])."%");

        if( $_REQUEST['customer_name'] != '' )
          $map['customer_name'] = array('eq',trim($_REQUEST['customer_name']));

        if( $_REQUEST['order_status'] != '' )
          $map['order_status'] = $_REQUEST['order_status'];
        
        if( $_REQUEST['status'] != '' )
          $map['status'] = $_REQUEST['status'];

        if( $_REQUEST['order_source_id'] != '' )
          $map['order_source_id'] = $_REQUEST['order_source_id'];
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //审核时间
                $map['check_time '] = $cond_time;
                break;
              case '2': //发货时间
                $map['shipping_time '] = $cond_time;
                break;
              case '3': //下单时间
                if (empty($_REQUEST['keywords']) && empty($_REQUEST['product_name']) ) {
                    
                    if($_REQUEST['etype'] == 'detail' ){ //导出订单详情，需按saleView进行搜索
                      $map['Sale'.$archive_suffix.'.create_time '] = $cond_time;
                    }else
                      $map['create_time '] = $cond_time;
                }else
                    $map['Sale'.$archive_suffix.'.create_time '] = $cond_time;
                break;
              case '4': //支付时间
                $map['pay_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

    }

    
    public function  index() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }

        $this->assign('meta_title','零售订单');

        if(empty($_REQUEST['keywords']) && empty($_REQUEST['product_name']) ){
          
          if(!empty($map)){
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
          }
          $sum_should_pay = M('Sale')->where($map)->sum('should_pay');
          $this->assign('sum_should_pay' ,$sum_should_pay);
          parent::index();
        }else { //view视图展示
            $model = D ('SaleProductView');
            if (! empty ( $model )) {
                $this->_list(D('SaleProductView'), $map, $sortBy = 'create_time desc', $asc = false,true);
            }
            $sum_should_pay = $model->where($map)->sum('should_pay');
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
            $this->assign('sum_should_pay' ,$sum_should_pay);
            $this->display ();
            return;
        }
        
    
    }

    //历史存档数据展示及搜索
    public function  archive() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }

        $this->assign('meta_title','历史零售订单');

        if(empty($_REQUEST['keywords']) && empty($_REQUEST['product_name']) ){
          
          if(!empty($map)){
            //pass parameters to export_order function
            $parameters = str_replace(__ACTION__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
          }
          $sum_should_pay = M('Sale_archive')->where($map)->sum('should_pay');
          $this->assign('sum_should_pay' ,$sum_should_pay);
          parent::index('Sale_archive');
        }else { //view视图展示
            $model = D ('Sale_archiveProductView');
            if (! empty ( $model )) {
                $this->_list($model, $map, $sortBy = 'create_time desc', $asc = false,true);
            }
            $sum_should_pay = $model->where($map)->sum('should_pay');
            //pass parameters to export_order function
            $parameters = str_replace(__ACTION__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
            $this->assign('sum_should_pay' ,$sum_should_pay);
            $this->display ();
            return;
        }
        
    
    }
    public function more(){
         $this->edit('Sale','more');    
    }

    //历史订单操作日志
    public function archive_more(){
         $this->edit('Sale_archive','archive_more');    
    }
    //历史存档订单查看
    public function archive_edit(){
         $this->edit('Sale_archive',"archive_edit");    
    }
    public function edit_shipping(){
         $this->edit('Sale','edit_shipping');    
    }
 
    //可发群发短信
    public function send_message(){
         
         if(!empty($_REQUEST['mobile']) && !empty($_REQUEST['msg']) ) {
            $mobile = trim($_REQUEST['mobile']);
            $msg = trim($_REQUEST['msg'])."【".trim($_REQUEST['shop_name'])."】";
            $t = A('OrderAPI')->sendMessages($mobile,$msg );
            if($t)
              $this->success("短信发送成功",false,5);
            else
              $this->error("短信发送失败，请重新发送！");
         }else{
             $count_order_source = M('Sale')->where('id in('.$_REQUEST['id'].')')->count('distinct(order_source_id)');
             if($count_order_source > 1)
                 $this->error('请选择同一店铺的订单发短信!');
              $map = array(
                  'id' => array('in',$_REQUEST['id']),              
              );
              $sale_topays = M('Sale')->where($map)->field('id,customer_name,shipping_name,mobile,create_time,order_source_id,remark')->findAll();
             $mobiles = array();
             $valid_ids = ""; //有效的订单ID
             foreach( $sale_topays as $k=> $value ){//去重手机号
                if(empty($value['mobile'])) //空手机 号不要
                    continue;
                $mobiles[$k] = $value['mobile'];    
                if($k == 0)
                    $valid_ids .=$value['id'];
                else
                    $valid_ids .=",".$value['id'];
             }
             $mobiles = array_unique($mobiles);
             $mobiles_str = implode(",", $mobiles);

            if(substr($valid_ids,0,1) == "," )
                $valid_ids = substr_replace($valid_ids,'',0,1); //去掉开头的,
             $this->assign('valid_ids',$valid_ids);
             $this->assign('mobiles',$mobiles_str);
             $this->assign('sale_to_notices',$sale_topays);
            $this->edit('Sale','send_message'); 
         } 
  }

    //修改客户物流信息,如地址,电话,收货人等.
    public function update_shipping(){
        $this->update();
    }

//显示平台待发货的订单 状态为：待发货，且有运单号及快递公司,是淘宝订单
    public function toshipping()
    {
      $map['order_status'] = 3;
      $map['is_shipping_mall'] = 0;
      //$map['logicompany_id'] = array('neq',0);
      //$this->index('SaleView');


        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        $model = D ('Sale');
        if (! empty ( $model )) {
            $this->_list(D('Sale'), $map, $sortBy = 'id', $asc = false,false);
        }
      $this->display();
    }

    //显示平台缺货，待发货的订单 状态为：待发货，没有运单号
    public function can_not_shipping()
    {
      $map['order_status'] = 2;
      $map['logino'] = '';
      //$this->index('SaleView');


        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        $model = D ('SaleView');
        if (! empty ( $model )) {
            $this->_list(D('SaleView'), $map, $sortBy = 'id desc', $asc = false,true);
        }
      $this->display();
    }

    public function export_order($value='')
    {
       //替换查询的函数，可以得map.再导出结果
      //file type: order,order_detail,both
      $archive_suffix = ""; //启用历史记录
      $export_type = $_REQUEST['etype'];
      switch ($_REQUEST['action']) {
        case 'can_not_shipping':
          $map['order_status'] = 2;
          $map['logino'] = '';
          break;
        case 'toshipping':
          $map['order_status'] = 2;
          $map['logino'] = array('neq','');
          $map['logicompany_id'] = array('neq',0);
          break;
        case 'archive':
            $archive_suffix = "_archive";
            break;
        default: //index
         
          break;
      }
      $map = $this->_search ();
      $this->_filter ( $map );
      $line = "";
      $data = array();
      $express = S('Express');
      $order_source = S('order_source');
      $goods = S('goods');
      switch ($export_type) {
             case 'order':
             if(empty($_REQUEST['keywords']) && empty($_REQUEST['product_name']) ){
                 $voList = D('Sale'.$archive_suffix)->where($map)->group('id')->findAll( );
             }
              else if(empty($_REQUEST['product_name']))
                $voList = D('Sale'.$archive_suffix.'View')->where($map)->group('sale_id')->findAll( );
              else
                $voList = D('Sale'.$archive_suffix.'ProductView')->where($map)->group('sale_id')->findAll( );
               $title ="订单号,原始单号,会员名,货款,运费,应付款,实付款,订单状态,买家留言,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,发货时间,物流单号,物流公司,订单备注,宝贝总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => "'".$value['sale_no'],
                     'mall_no' => "'".$value['mall_no'],
                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['sale_no']),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                     'real_pay' => $value['sum_pay'], //暂用理论总金额 代替实付款
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      'customer_msg' => iconv('utf-8','GBK',$value['customer_msg'] ),
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      

                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),
                      'shipping_time' => toDate($value['shipping_time']),

                      'logino' => $value['logino'],
                      'logicompany' => iconv('utf-8','GBK',$express[$value['logicompany_id'] ]['name'] ), //中文转码 
                      
                      'remark' => iconv('utf-8','GBK',$value['remark']),
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK', $order_source[$value['order_source_id']] ),
                     );
                    $line .= build_csv_line($data);
                    unset($data);
                } 
                $filename = "DYW_order".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);
               break;
            case 'detail':
               $common_products = S('products');
               if(empty($_REQUEST['product_name']))
                   $voList = D('Sale'.$archive_suffix.'View')->where($map)->findAll( );
               else
                   $voList = D('Sale'.$archive_suffix.'ProductView')->where($map)->findAll( );
               if(empty($voList))
               $this->error("无数据可导出");
               $category = S('category');
               $title ="订单号,会员名,商品名称,销售标题,所属产品,商品类别,单价,数量,小计,发货时间\n";
                $title = iconv('utf-8', 'GBK', $title);
                $data = array();
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $common_id = $goods[$value['product_id']]['common_id'];
                  $data= array(
                     'sale_no' => "'".$value['sale_no'],
                     'customer_name' => iconv('utf-8', 'GBK',$value['customer_name'] ),
                     'pname' => iconv('utf-8', 'GBK',$goods[$value['product_id']]['name'] ),
                     'sale_title' => iconv('utf-8', 'GBK',$value['sale_title'] ),
                     'common_product' => iconv('utf-8', 'GBK',$common_products[$common_id]['name'] ), //所属产品
                     'cat_id' => iconv('utf-8', 'GBK',$category[$goods[$value['product_id']]['cat_id']]), //类别
                     'price' => $value['price'],
                     'number' => $value['number'],
                     'total' => $value['dtotal'],
                     'shipping_time' => toDate($value['shipping_time'])
                     );
                   $line .= build_csv_line($data);
                    unset($data);
                }
                $filename = "DYW_goods".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);

               break;
             case 'both':

             default:
               if(empty($_REQUEST['keywords']) && empty($_REQUEST['product_name']) )
                $voList = D('Sale'.$archive_suffix)->where($map)->group('id')->findAll( );
              else if(empty($_REQUEST['product_name']))
                $voList = D('Sale'.$archive_suffix.'View')->where($map)->group('sale_id')->findAll( );
              else
                $voList = D('Sale'.$archive_suffix.'ProductView')->where($map)->group('sale_id')->findAll( );


               $title ="订单号,原单号,会员名,货款,运费,应付款,实付款,订单状态,买家留言,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,物流单号,物流公司,订单备注,宝贝总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => "'".$value['sale_no'],
                     'mall_no' => "'".$value['mall_no'],
                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['sale_no']),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                     'real_pay' => $value['sum_pay'], //暂用理论总金额 代替实付款
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      'customer_msg' => iconv('utf-8','GBK',$value['customer_msg'] ),
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      

                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),

                      'logino' => $value['logino'],
                      'logicompany' => iconv('utf-8','GBK',$express[$value['logicompany_id'] ]['name'] ), //中文转码 
                      
                      'remark' => iconv('utf-8','GBK',$value['remark']),
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK',$order_source[$value['order_source_id']] ),
                     );
                  $line .= build_csv_line($data);
                    unset($data);
                    $goods_detail = M('Sale_detail'.$archive_suffix)->where('sale_no ="'.$value['sale_no'].'"')->findAll();
                    foreach ($goods_detail as  $v) {
                      $goods_data= array(
                       'blank' => "",
                       'sale_title' => iconv('utf-8', 'GBK',$v['sale_title'] ),
                       'pname' => iconv('utf-8', 'GBK',$goods[$v['product_id']]['name'] ),
                       
                       'product_id' => $v['product_id'],
                       'out_number' => $v['out_number'],
                       'price' => $v['price'],
                       'number' => $v['number'],
                       'total' => $v['total']
                     );
                      $line .= build_csv_line($goods_data);
                    }
                    
                }

                $filename = "DYW_OrderGoods".date('Ymd_His').'.csv'; //设置文件名 
                export_csv($filename,$title.$line);
               break;
           }     
    }

    public function _before_update()
    {
      $shipping = array(
          'id' => $_POST['shipping_address_id'],
          'customer_id' => $_POST['customer_id'],
        );
       if( !empty($_POST['shipping_name']) )
          $shipping['name'] = trim($_POST['shipping_name']);
      if( !empty($_POST['mobile']) )
          $shipping['mobile'] = trim($_POST['mobile']);
      if( !empty($_POST['phone']) )
          $shipping['phone'] = trim($_POST['phone']);
      if( !empty($_POST['address']) )
          $shipping['address'] = trim($_POST['address']);
      //更新收货人地址信息
      M('Shipping_address')->save($shipping);
      //如果订单由待审核变为审核通过，并且内部货品编码不为0时，则记录此时的审核时间，并审核通过
      if($_POST['status'] == 1  && getModelName( $_POST['id'],'Sale','status') == 0
         && $this->check_pid_zero($_POST['id'] ) ){
          $_POST['check_time'] = time();
          //split order
          SaleModel::split_order($_POST['id']);

          // 记录客服备注的处理状态
          if(!empty($_POST['msg_id']) && count($_POST['msg_id']) > 0 ){
             $count_msg = count($_POST['msg_id']);
             for($i=0; $i < $count_msg; $i++ ){
                 $msg_data = array(
                     'id' => $_POST['msg_id'][$i],
                     'status' => $_POST['process_status'][$i],
                     'receiver_id' => $_POST['receiver_id'][$i],
                     'update_time' => $_POST['msg_utime'][$i],
                 );
                 M('Message')->save($msg_data);
             }
          }

      }else{
        if(! $this->check_pid_zero($_POST['id']) )
           $this->error("商品编号不应为0，请重新审核！");
      }
        
     
    }

    public function update()
    {
      $name=$this->getActionName();
        $model = D ( $name );

        $id = $_POST['id'];
        $ids = strpos($id,',') === false ? $id : explode(',', $id);
        if(!empty($_POST['logino']) && !empty($_POST['logicompany_id']) )
          $this->check_logino($_POST['logino'],$_POST['logicompany_id']);

        if(is_array($ids)){ 
        //批量更新，特别是订单合并的情况，适用于订单合并后，统一发货的
            foreach ($ids as  $value) {
              $id = $value;
              $_POST['id'] = $id;
                $old = $model->where('id = '.$id)->find();
                //如果是发货，则检查库存，库存不足，不能发货
                if($old['order_status'] == 2 && $_POST['order_status'] ==3 ){
                    $this->check_stock($id); //检查库存
                    if(empty($_POST['logino']))
                      $this->error("请输入快递单号！");
                }
                    

                if (false === $model->create ()) {
                    $this->error ( $model->getError () );
                }
                // 更新数据
                $list=$model->save ();
                if (false !== $list) {
                    //$this->update_cache( $name );
                    $new = $model->where('id = '.$id)->find();
                    //如果由待发货改为已发货，则更新库存,同时提交 到第三方平台发货
                    $express = S('express');
                    if($old['order_status'] ==2  && $new['order_status'] ==3 ){
                       $this->update_sale_stock($new['id']);
                       if($old['order_source_id'] < 4 or $old['order_source_id'] == 9 )
                          jw_shipping( $new['sale_no'],$express[$_POST['logicompany_id']]['name'],$_POST['logino'],$_POST['logicompany_id'] ,$new['order_source_id'],$new['mobile']);
                       else if($old['order_source_id'] >4 and $old['order_source_id'] < 7  ){//德生堂订单
                          A('OrderAPI')->dst_shipping($new['sale_no'],$_POST['logino'],$_POST['logicompany_id']);
                          $this->shipping_notice($new['mobile'] , $express[$_POST['logicompany_id']]['name'],$_POST['logino'], $new['order_source_id']);
                       }
                    }
                      

                    $mod_field = getModelName ($id, $name,$field);
                    //如果未取到字段值 ，则返回对应的ID编号
                    $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
                    if('Action' != $name)
                        A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
                    //成功提示

                    //更新库存
                    
                } else {
                    //错误提示
                    $this->error ('编辑失败!');
                }
            }

            $jumpUrl = $_REQUEST['jumpUrl'];
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('编辑成功!',false,0.01);
        }else{
              //单个处理
            $old = $model->where('id = '.$id)->find();
            //如果是发货，则检查库存，库存不足，不能发货
           if($old['order_status'] == 2 && $_POST['order_status'] ==3 ){
                    $this->check_stock($id); //检查库存
                    if(empty($_POST['logino']))
                      $this->error("请输入快递单号！");
                }

            if (false === $model->create ()) {
                $this->error ( $model->getError () );
            }
            // 更新数据
            $list=$model->save ();
            if (false !== $list) {
                $new = $model->where('id = '.$id)->find();
                $mod_field = getModelName ($id, $name,$field);

                //如果由待发货改为已发货，则更新库存
                $express = S('express');
                if($old['order_status'] ==2  && $new['order_status'] ==3 ){
                  //京卫发货
                  if($old['order_source_id'] < 4 or $old['order_source_id'] == 9 ) //当当
                     jw_shipping( $new['sale_no'],$express[$_POST['logicompany_id']]['name'],$_POST['logino'],$_POST['logicompany_id'] , $new['order_source_id'],$new['mobile']);
                  else if($old['order_source_id'] >4 and $old['order_source_id'] < 7  ){//德生堂订单
                      A('OrderAPI')->dst_shipping($new['sale_no'],$_POST['logino'],$_POST['logicompany_id']);
                      $this->shipping_notice($new['mobile'] , $express[$_POST['logicompany_id']]['name'],$_POST['logino'], $new['order_source_id']);
                  }
                  $this->update_sale_stock($new['id']);
                }
                       

                //如果未取到字段值 ，则返回对应的ID编号
                $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
                if('Action' != $name)
                    A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
                //成功提示
                $jumpUrl = $_REQUEST['jumpUrl'];
                if(empty($jumpUrl))
                    $jumpUrl = Cookie::get ( '_currentUrl_' );
                $this->assign ( 'jumpUrl', $jumpUrl );
                //如果已经打印配货单，修改了地址或收货人，则提示通知仓库注意
                if( ($old['prepare_status'] == 1 || $old['prepare_status'] == 2)
                    && ( $old['shipping_name'] != $new['shipping_name'] || $old['address'] != $new['address']  )
                   ){
                    $content = "修改了地址或收货人,需要重新打印配货单";
                    A('Message')->write_message($id,2,$content,$_SESSION[C('USER_AUTH_KEY')]);
                    $this->success('修改成功。<br/>该单正在配货中，请通知仓库调整！',false,10);
                }else
                  $this->success ('编辑成功!',false,0.01);
            } else {
                //错误提示
                $this->error ('编辑失败!');
            }

        }
        
        } //主要用于闪电发货
        public function mass_update() {
            $data = $_POST; $count_no = count($data['logino']);
       
        for($i =0; $i < $count_no;$i++) {
          //check logino
          if(!is_numeric($data['logino'][$i]) || strlen($data['logino'][$i])< 12 || $data['logino'][$i] ==''  )
            continue;
          
          $_POST = array(
            'id' => $data['id'][$i],
            'shipping_time' => $data['shipping_time'][$i],
            'logino' => $data['logino'][$i],
            'order_status' => $data['order_status'][$i],
            'logicompany_id' => $data['logicompany_id'][$i],
            );

          $ids = strpos($_POST['id'],',') === false ? $_POST['id'] : explode(',', $_POST['id'] );
          if(is_array($ids)){ //适用于以,分隔的订单号--合并情况
            foreach ($ids as  $value) {
              $id = $value;
              $_POST['id'] = $id;
              $this->micro_update($id);
            }
          }else
            $this->micro_update($ids);

          unset($_POST);
        }

        $jumpUrl = $_REQUEST['jumpUrl'];
        if(empty($jumpUrl))
            $jumpUrl = Cookie::get ( '_currentUrl_' );
        $this->assign ( 'jumpUrl', $jumpUrl );
        $this->success ('闪电发货成功!');
    }

    //更新数据，但不返回提示，不终止。适用于批量更新操作
    public function micro_update($id)
    {
      $name=$this->getActionName();
        $model = D ( $name );
      $old = $model->where('id = '.$id)->find();

      //如果是发货，则检查库存，库存不足，不能发货
            if($old['order_status'] == 2 && $_POST['order_status'] ==3 )
                    $this->check_stock($id);

            if (false === $model->create ()) {
                $this->error ( $model->getError () );
            }
            // 更新数据
            $list=$model->save ();
            if (false !== $list) {
                $new = $model->where('id = '.$id)->find();
                $mod_field = getModelName ($id, $name,$field);

                //如果由待发货改为已发货，则更新库存
                $express = S('express');
                    if($old['order_status'] ==2  && $new['order_status'] ==3 ){
                      //京卫发货
                      if($old['order_source_id'] < 4 or $old['order_source_id'] == 9 )
                        jw_shipping( $new['sale_no'],$express[$_POST['logicompany_id']]['name'],$_POST['logino'] ,$_POST['logicompany_id'],$new['order_source_id'],$new['mobile']);
                      else if($old['order_source_id'] >4 and $old['order_source_id'] < 7  ){//德生堂订单
                          A('OrderAPI')->dst_shipping($new['sale_no'],$_POST['logino'],$_POST['logicompany_id']);
                          $this->shipping_notice($new['mobile'] , $express[$_POST['logicompany_id']]['name'],$_POST['logino'], $new['order_source_id']);
                      } 
                      $this->update_sale_stock($new['id']);
                    }

                //如果未取到字段值 ，则返回对应的ID编号
                $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
                if('Action' != $name)
                    A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
            }
    }

    //快速出货--销售
    public function fastadd(){
        $this->assign('logicompany',C('logicompany'));
        $this->assign('users',getModelIdName('User'));
        $this->assign('warehouses',getModelIdName('Warehouse'));
        $this->assign('customers',M('Customer')->where('status=1')->order('sort')->getField('id,name'));
        $enter_id = $_REQUEST['enter_id'];
        $condition = array ('enter_id' => array ('in', explode ( ',', $enter_id ) ) );
        $products = M('Enter_detail')->alias('a')->join('vm_Product p on a.product_id = p.id')
                ->where($condition)
                ->field('a.product_id,a.number,p.tm,p.name,p.wholesale_price_default,p.sale_price_default,p.unit_id')->findAll();
        $this->assign('products',$products);
        //默认同一批出的货来自同一个仓库
        $this->assign("warehouse_id",  getModelName($enter_id,'Enter','warehouse_id'));
        $this->display();
    }

    //import enter product detail
    public function import(){
        $sheetData = A('Import')->getExcel();
        $Product = M('Product');
        $product_str = "";
        $data = array();
        $i = 1; //count success import record
        foreach ($sheetData as $key => $value) {
            if ($key > 1) {//从第二行开始读取
              //如果条码及名称全无，则跳过
                if(empty($value['A']) && empty ($value['B']) ){
                  $data = null;
                  continue;
                }

               $data = array(
                   'tm' => trim($value['A']),   //条码
                   'name' => trim($value['B']), //品名
                   'number' => trim($value['C']),   //数量
                   'price' => trim($value['D']),   //售价
               );
                    
                    //不使用对象$Product->name 以免继承使用之前的值
                    //优先取条码名，如果条码为空，则取第二列的产品名称
                    $pt =  empty($data['tm']) ? $Product->getByName($data['name']) : $Product->getByTm($data['tm']) ;
                    if(empty($pt) )
                      $pt = $Product->getByName($data['name']);

                    $name = $pt['name']; 
                if ( empty($name)) {
                  //异常记录显示出来，人工去重后再进行插入操作
                  $data = array(
                    'name' => '<font color="red">EXCEL第  '.$key.'  行异常,请删除</font>'
                    );
                }else{
                    $data['name'] = $name;
                    $sale_price_default = $Product->sale_price_default;
                    $data['price'] = empty($data['price'] ) ? $sale_price_default : $data['price'];
                }
                //json only filter td,not li ,so use li to stand out
            $data['unit'] = getModelName($Product->unit_id, 'Unit');
            
            $wholesale_price_default = $Product->wholesale_price_default;
            
            $product_str .= "<tr class='tLeft' id='product_td'>";
            $product_str .="<td>" . $data['tm'] . '</td>';
            $product_str .="<td><input type='hidden' name='product_id[]' value='" . $Product->id. "'/> <p class='span5'>" . $data['name'] . '</p></td>';
            $product_str .="<td>" . printLensOption($Product->id). "</td>";
            $product_str .="<td>销售价:".$sale_price_default . ",零售价:".$wholesale_price_default."</td>";
            $product_str .="<td><input type='text' class='input-mini' name='price[]' value='" . $data['price']. "'/></td>";
            $product_str .="<td><input type='text' class='input-mini ' tabindex=1 name='number[]' value='".$data['number']."' /></td>";    //数量
            $product_str .="<td class='span1'>" . $data['unit'] . "</td>";    //单位
            $product_str .="<td class='span1'>" . getStock($Product->id,1) . "</td>";    //库存,暂时默认青云路仓库TODO
            $product_str .="<td><input type='text' class='input-small' name='lot[]' value='' /></td>";   //产品批号
            $product_str .="<td><input type='text' class='input-small' name='exp[]' onClick='WdatePicker()' value='' /></td>";   //有效期
            
            
           $product_str .=  " <td class='span1'><img src='".__APP__."/Public/images/publish_x.png' alt='删除' onclick='removerow(this);'/>".$i."</td></tr>";
            $data = null;
            $i++;
            }
        }
        echo "{";
        echo                "error: '" . $error . "',\n";
        echo                "msg: '" . urlencode(($product_str)) . "'";
        echo "}";
       
    }

    //import 111.com.cn order list 
    public function import_111order(){
        $sheetData = A('Import')->getExcel();
        $Product = M('Product');
        $product_str = "";
        $sdata = array();
        $sale_detail = M('Sale_detail');
        $sale = M('Sale');

        $i = 0; //count success import record
        foreach ($sheetData as $key => $data) {
            if ($key < 2) //从第二行开始读取
                continue;
              //如果条码及名称全无，则跳过
             if(empty($data['A']) && empty ($data['B']) ){
                $sdata = null;
                continue;
             }
         //订单插入
         $exist_sale = $sale->where('sale_no="'.trim($data['A']).'"')->field('id,sum_number,total')->find();
         if(!$exist_sale ){ //create new order
           $sdata = array(
               'sale_no' => trim($data['A']),
               'mall_no' => trim($data['A']), //第三方订单号,still 111.com.cn order number
               'customer_name' => trim($data['F']),//会员名
               //转化为我方货款
               'total' => 0, //TODO 累加 
               'logifee' => trim($data['AA']),
               'sum_pay' => trim($data['E']), //理论应付款：总金额，暂取实付款
               //我方应付款= 我方货款+运费 -- 折价需处理
               'should_pay' => trim($data['E']) ,    
               'real_pay' => trim($data['E']),  //买家实际支付金额,可能包含第三方货款
               // 订单状态转换统一的
               'order_status' => 2, //等待发货

               'customer_msg' => trim($data['AB']),
               'create_time' => strtotime( trim($data['G']) ),
               'pay_time' =>  strtotime( trim($data['G']) ),  //支付时间暂等于下单时间
               'invoice_title' => trim($data['R']),
               //shipping address info
               'shipping_name' => trim($data['L']),
               'address' => trim($data['H']).trim($data['I']).trim($data['J']).trim($data['K']),

               'province' => trim($data['H']), //省份
               'city' => trim($data['I']), //市
               'county' => trim($data['J']),  //区或县

               'phone' => trim($data['N']),
               'mobile' => trim($data['M']),
               'order_source_id' => 4, //壹药网来源订单
               'warehouse_id' => 1,
               'user_id' => $_SESSION[C('USER_AUTH_KEY')],
               'sum_number' => 0,//TODO

           );
           // 新增会员 或获取已有会员ID 淘宝可用
           $customer_id = getCustomerId($sdata['customer_name'],'',$sdata['mobile'],$sdata['phone'] );
           $sdata['customer_id'] = $customer_id ;
           $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata['phone'] );
           $sdata['shipping_address_id'] = $shipping_address_id ;
           $sale_id = $sale -> add($sdata);
          }else
              $sale_id = $exist_sale['id'];
         //商品明细插入

         $out_number = str_replace('\'','',trim($data['S']) );
        $old_goods = $sale_detail->where('sale_id ='.$sale_id.' and out_number="'.$out_number.'"')->getField('id');
         if(! $old_goods ){
           $goods_data = array(
            'sale_no' => trim($data['A']),
            'sale_title' => trim($data['T']),
            'price' => trim($data['W']),
            'number' => trim($data['V']),
            'total' => $data['X'],
           'out_number' => $out_number,
           'warehouse_id' => 1, //默认第一个仓库
            'product_id' => getMyGoodsId_real( 4, $out_number ),  //对应货品ID，不是产品
            'sale_id' => $sale_id,
            'create_time' => time(),
          );
           $sdid = $sale_detail -> add($goods_data);
           if($sdid){ //sum total,sum_number to sale table
               $sum_data = array(
                   'total'=> !is_array($exist_sale) ? $goods_data['total'] : ($exist_sale['total'] + $goods_data['total'] ),
                   'sum_number' => !is_array($exist_sale) ? $goods_data['number'] : ( $exist_sale['sum_number']+$goods_data['number']  )
               );
               $sale->where('id = '.$sale_id)->save($sum_data);
           }
            $i++;
         }
         unset($sdata);
        $goods_data = null;
        }
      $this->success("成功导入 ".$i." 条订单！",false,6); 
    }
    //import taobao order
    public function import_order(){
        $inputFileName = A('Import')->getCsv();
        $file_type = $_POST['file_type'];
        $jw_map = getPmap(1); //京卫匹配的产品列表 Out_number=> my_number

        $goods = S('goods'); //缓存货品信息
        $sale_detail = M('Sale_detail');
        $sale = M('Sale');
        $customer = M('Customer');
        $shipping_address = M('Shipping_address');
        $sdata = array(); // get line data from csv
        $i = 0; //统计有多少 条记录成功导入
        //注意：导入字体以gb2312解析，字库不全，繁体及生僻字无法解析，必须使用GBK
        switch ($file_type) {
            case '1'://京卫淘宝商品明细
            {
                if(!strpos($inputFileName, 'OrderDetailList')){
                    $this->error('请上传淘宝商品明细，文件名为OrderDetailList字样');
                }
                $row = 1;
                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                    if($row > 1 
                        && getOrderStatus(trim(iconv('GBK','utf-8',$data['8'])) ) != 1 //过滤掉等待付款的订单
                         && getOrderStatus(trim(iconv('GBK','utf-8',$data['8'])) ) != 0 //过滤掉待付款的订单 --未创建支付宝交易
                         && $product_id = $jw_map[trim($data['4'])]
                         && is_numeric(trim($data['0'] ) ) //只有订单号是数字的才导入
                         && !checkExistOrder_detailRecord(trim($data['0']), trim($data['4']),trim(iconv('GBK','utf-8',$data['5'])) ) //过滤掉重复录入的
                         
                          ) { 
                        //start from second line
                        //过滤掉非我方产品  
                       //禁止重复导入
                       $sdata = array(
                           'sale_no' => trim($data['0']),
                           'sale_title' => trim(iconv('GBK','utf-8',$data['1'])),
                           'price' => trim($data['2']),
                           'number' => trim($data['3']),
                           'total' => $data['2'] * $data['3'],
                           'out_number' => trim($data['4']),
                           'options' => trim(iconv('GBK','utf-8',$data['5'])),
                           'warehouse_id' => 1, //默认第一个仓库
                           'product_id' => getMyGoodsId( trim($data['4']),  trim(iconv('GBK','utf-8',$data['5'])) ),  //对应货品ID，不是产品
                           'create_time' => time(),

                       );
                       $new_warehouse_id = intval($goods[$sdata['product_id']]['warehouse_id']); //根据货品仓库更新订单商品仓库
                       $sdata['warehouse_id'] = $new_warehouse_id == 0 ? 1 : $new_warehouse_id; //如果为0,则取默认仓库 
                       $new_sdid = $sale_detail->add($sdata);
                       if($new_sdid)
                           $i++;
                       unset($sdata);
                    }
                    $row++;
                }
                fclose($handle);
                }
                $this->success("成功导入 ".$i." 条淘宝商品明细!",false,5);
                $i = 0;
                break;
            }

            case '7'://亚洲 淘宝商品明细
            {
                if(!strpos($inputFileName, 'OrderDetailList')){
                    $this->error('请上传淘宝商品明细，文件名为OrderDetailList字样');
                }
                $row = 1;
                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                    if($row > 1
                         && is_lens_order(trim(iconv('GBK','utf-8',$data['1'])) ) === true //过滤掉非隐形眼镜商品
                         && getOrderStatus(trim(iconv('GBK','utf-8',$data['8'])) ) != 1 //过滤掉等待付款的订单
                         && getOrderStatus(trim(iconv('GBK','utf-8',$data['8'])) ) != 0 //过滤掉待付款的订单 --未创建支付宝交易
                         && !checkExistOrder_detailRecord_tb( trim($data['0']), trim($data['4']),0 )  //过滤掉重复录入的.亚洲的直接传过来商品编号
                          ) { 
                        //start from second line
                        //过滤掉非我方产品  
                       //禁止重复导入
                       $sdata = array(
                           'sale_no' => trim($data['0']),
                           'sale_title' => trim(iconv('GBK','utf-8',$data['1'])),
                           'price' => trim($data['2']),
                           'number' => trim($data['3']),
                           'total' => $data['2'] * $data['3'],
                           'out_number' => trim($data['4']),
                           'options' => trim(iconv('GBK','utf-8',$data['5'])),
                           'warehouse_id' => 1, //默认第一个仓库
                           'product_id' => trim($data['4']),  //对应货品ID，不是产品
                           'create_time' => time(),

                       );
                       $new_warehouse_id = intval($goods[$sdata['product_id']]['warehouse_id']); //根据货品仓库更新订单商品仓库
                       $sdata['warehouse_id'] = $new_warehouse_id == 0 ? 1 : $new_warehouse_id; //如果为0,则取默认仓库 
                       $new_sdid = $sale_detail->add($sdata);
                       if($new_sdid)
                           $i++;
                       unset($sdata);
                    }
                    $row++;
                }
                fclose($handle);
                }
                $this->success("成功导入 ".$i." 条淘宝商品明细!",false,5);
                $i = 0;
                break;
            }
               
                
            case '2'://京卫淘宝订单
                {
                   if(!strpos($inputFileName, 'OrderList') ) 
                   {
                    $this->error('请上传淘宝订单文件，文件名为OrderList字样');
                   }
                $row = 1;
                $sale_no_data = array(); //存入订单号

                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle,  0, ',', '"', '"')) !== FALSE) {
                  // 过滤掉非我方订单 -- 从订单详情里找订单编号匹配筛选 
                  //避免重复导入
                    if($row > 1 
                          && getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) != 1 //过滤掉等待付款的订单 
                          && getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) != 0 //过滤掉待付款的订单 --未创建支付宝交易
                          && is_numeric(trim($data['0'] ) ) //只有订单号是数字的才导入
                          && shouldAddOrder( trim($data['0'] ) )
                     ) { //start from second line
                       $full_address = get_tb_address( trim(iconv('GBK','utf-8',$data['13'])) );

                       $sdata = array(
                           'sale_no' => trim($data['0']),
                           'mall_no' => trim($data['0']), //第三方订单号
                           'customer_name' => trim(iconv('GBK','utf-8',$data['1'])),//会员名
                           'alipay' => trim(iconv('GBK','utf-8',$data['2'])),
                           //转化为我方货款
                           'total' => getGoodsTotalMoney( trim($data['0']) ), 
                           'logifee' => trim($data['4']),
                           'sum_pay' => trim($data['6']), //理论应付款：总金额，有可能包括对方货款
                           //我方应付款= 我方货款+运费 -- 折价需处理
                           'should_pay' => $this->get_should_pay(( getGoodsTotalMoney( trim($data['0']) ) + trim($data['4']) ), $data['8'] ) ,    
                           'real_pay' => trim($data['8']),  //买家实际支付金额,可能包含第三方货款
                           // 订单状态转换统一的
                           'order_status' => getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ),

                           'customer_msg' => trim(iconv('GBK','utf-8',$data['11'])),
                           'create_time' => strtotime( trim($data['17']) ),
                           'pay_time' => empty($data['18']) ? 0: strtotime( trim($data['18']) ),  //支付时间
                           'logicompany' => trim(iconv('GBK','utf-8',$data['22'])), 
                           'logicompany_id' => !empty($data['22']) ? getExpressId( trim(iconv('GBK','utf-8',$data['22'])) ) : 0, // exchange to id
                           'logino' => !empty($data['21'])?substr( trim($data['21']), 3) : '',  //exclude No:
                           
                           'invoice_title' => trim(iconv('GBK','utf-8',$data['30'])),

                           //shipping address info
                           'shipping_name' => trim(iconv('GBK','utf-8',$data['12'])),
                           'address' => trim(iconv('GBK','utf-8',$data['13'])),

                           'province' => $full_address['province'], //省份
                           'city' => $full_address['city'], //市
                           'county' => $full_address['county'],  //区或县

                           'phone' => trim(iconv('GBK','utf-8',$data['15'])),
                           'mobile' => fixMobile(trim(iconv('GBK','utf-8',$data['16'])) ),
                           'remark' => trim(iconv('GBK','utf-8',$data['23'])) , //商家备注
                           'order_source_id' => 3, //淘宝来源订单
                           'warehouse_id' => 1,
                           'user_id' => $_SESSION[C('USER_AUTH_KEY')],
                           'sum_number' => getSumNumber( trim($data['0']) ),

                       );
                        //部分发货订单转换成待发货，需要去掉原来的发货单号及快递公司
                        if($sdata['order_status'] == 2 && $sdata['logino'] != "" ){
                          $sdata['logicompany'] = ""; 
                           $sdata['logicompany_id'] = 0; 
                           $sdata['logino'] = '';
                        }
                           // 新增会员 或获取已有会员ID 淘宝可用
                       $customer_id = getCustomerId($sdata['customer_name'],$sdata['alipay'] );
                       $sdata['customer_id'] = $customer_id ;
                       $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata['phone'] );
                       $sdata['shipping_address_id'] = $shipping_address_id ;
                       $sale_id = $sale -> add($sdata);
                       //将sale_detail表中相应的sale_id 补全
                       $sale_detail ->where('sale_no ="'.$sdata['sale_no'].'"')->setField('sale_id',$sale_id);
                       
                       $sale_no_data[$i] = $sdata['sale_no'];
                       unset($sdata);
                       $i++;
                    }
                    $row++;
                }
                fclose($handle);
                }
                GiftAction::mass_add_gift($sale_no_data);
                SaleModel::auto_split_mass_order();

                $this->success("成功导入 ".$i." 条订单",false,5);
                break;
            }

            case '8'://亚洲 淘宝订单
                {
                   if(!strpos($inputFileName, 'OrderList') ) 
                   {
                    $this->error('请上传淘宝订单文件，文件名为OrderList字样');
                   }
                $row = 1;
                $sale_no_data = array(); //存入订单号

                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle,  0, ',', '"', '"')) !== FALSE) {
                  // 过滤掉非我方订单 -- 从订单详情里找订单编号匹配筛选 
                  //避免重复导入
                    if($row > 1 
                          && getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) != 1 //过滤掉等待付款的订单 
                          && getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) != 0 //过滤掉待付款的订单 --未创建支付宝交易
                          && shouldAddOrder( trim($data['0'] ) )
                     ) { //start from second line
                       $full_address = get_tb_address( trim(iconv('GBK','utf-8',$data['13'])) );
                       $sdata = array(
                           'sale_no' => trim($data['0']),
                           'mall_no' => trim($data['0']), //第三方订单号
                           'customer_name' => trim(iconv('GBK','utf-8',$data['1'])),//会员名
                           'alipay' => trim(iconv('GBK','utf-8',$data['2'])),
                           //转化为我方货款
                           'total' => getGoodsTotalMoney( trim($data['0']) ), 
                           'logifee' => trim($data['4']),
                           'sum_pay' => trim($data['6']), //理论应付款：总金额，有可能包括对方货款
                           //我方应付款= 我方货款+运费
                           'should_pay' => $this->get_should_pay( ( getGoodsTotalMoney( trim($data['0']) ) + trim($data['4']) ), $data['8'] ) ,    
                           'real_pay' => trim($data['8']),  //买家实际支付金额,可能包含第三方货款
                           // 订单状态转换统一的
                           'order_status' => getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ),

                           'customer_msg' => trim(iconv('GBK','utf-8',$data['11'])),
                           'create_time' => strtotime( trim($data['17']) ),
                           'pay_time' => empty($data['18']) ? 0: strtotime( trim($data['18']) ),  //支付时间
                           'logicompany' => trim(iconv('GBK','utf-8',$data['22'])), 
                           'logicompany_id' => !empty($data['22']) ? getExpressId( trim(iconv('GBK','utf-8',$data['22'])) ) : 0, // exchange to id
                           'logino' => !empty($data['21'])?substr( trim($data['21']), 3) : '',  //exclude No:
                            
                           //'is_morder' => trim(iconv('GBK','utf-8',$data['31'])),  //手机订单 暂时做为订单完毕的标记
                           'invoice_title' => trim(iconv('GBK','utf-8',$data['30'])),

                           //shipping address info
                           'shipping_name' => trim(iconv('GBK','utf-8',$data['12'])),
                           'address' => trim(iconv('GBK','utf-8',$data['13'])),

                           'province' => $full_address['province'], //省份
                           'city' => $full_address['city'], //市
                           'county' => $full_address['county'],  //区或县

                           'phone' => trim(iconv('GBK','utf-8',$data['15'])),
                           'mobile' => fixMobile(trim(iconv('GBK','utf-8',$data['16'])) ),
                           'remark' => trim(iconv('GBK','utf-8',$data['23'])) , //商家备注
                           'order_source_id' => 7, //亚洲淘宝来源订单
                           'warehouse_id' => 1,
                           'user_id' => $_SESSION[C('USER_AUTH_KEY')],
                           'sum_number' => getSumNumber( trim($data['0']) ),

                       );
                        //部分发货订单转换成待发货，需要去掉原来的发货单号及快递公司
                        if($sdata['order_status'] == 2 && $sdata['logino'] != "" ){
                          $sdata['logicompany'] = ""; 
                           $sdata['logicompany_id'] = 0; 
                           $sdata['logino'] = '';
                        }

                           // 新增会员 或获取已有会员ID 淘宝可用
                       $customer_id = getCustomerId($sdata['customer_name'],$sdata['alipay'] );
                       $sdata['customer_id'] = $customer_id ;
                       $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata['phone'] );
                       $sdata['shipping_address_id'] = $shipping_address_id ;
                       $sale_id = $sale -> add($sdata);
                       //将sale_detail表中相应的sale_id 补全
                       $sale_detail ->where('sale_no ="'.$sdata['sale_no'].'"')->setField('sale_id',$sale_id);
                       
                       $sale_no_data[$i] = $sdata['sale_no'];
                       unset($sdata);
                       $i++;
                    }
                    $row++;
                }
                fclose($handle);
                }
                GiftAction::mass_add_gift($sale_no_data);// 亚洲订单暂时不适用赠品，因编码不用common_id
                SaleModel::auto_split_mass_order();

                $this->success("成功导入 ".$i." 条订单",false,5);
                break;
            }

            case '3'://京卫药房网商品明细
                {
                   if(!strpos($inputFileName, 'Good_Info') ) 
                   {
                    $this->error('请上传药房网商品文件，文件名为Order_Good_INFO字样');
                   }
                $row = 1;
                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 0,',', '"', '"')) !== FALSE) {
                       $sale_title =  trim(iconv('GBK','utf-8',$data['2']));
                    if($row > 1 && !checkExistOrder_detailRecord(trim($data['0']), trim($data['1']) ,$sale_title, 0 )
                        && is_numeric(trim($data['0'] ) ) //只有订单号是数字的才导入
                     ) { //start from second line
                       // 避免重复录入-- 从订单详情里找订单编号匹配筛选
                      //改为优先导入淘宝订单时，会造成药房网重复导入淘宝订单
                       $sdata = array(
                           'sale_no' => trim($data['0']),
                           'out_number' => trim($data['1']),
                           'sale_title' => $sale_title ,
                           'price' => trim($data['8']),
                           'number' => trim($data['9']),
                           'total' => trim($data['10']),
                           //option value need to extract from goods_title last place
                           'warehouse_id' => 1, //默认第一个仓库
                           'product_id' => getMyGoodsIdJw( trim($data['1']),$sale_title  ), //获得货品ID
                           'create_time' => time(),

                       );
                       $new_warehouse_id = intval($goods[$sdata['product_id']]['warehouse_id']); //根据货品仓库更新订单商品仓库
                       $sdata['warehouse_id'] = $new_warehouse_id == 0 ? 1 : $new_warehouse_id; //如果为0,则取默认仓库 
                       $new_sdid = $sale_detail->add($sdata);
                       if($new_sdid)
                           $i++;
                       unset($sdata);
                    }
                    $row++;
                }
                fclose($handle);
                }
                $this->success('成功导入 '.$i.' 条京卫药房网商品记录',false,5);
                break;
            }
            default: //京卫药房网订单明细
               {
                   if(!strpos($inputFileName, 'order1') ) 
                   {
                    $this->error('请上传药房网订单文件，文件名为order1字样');
                   }
                $row = 1;
                $sale_no_data = array(); //存入订单号
                if (($handle = fopen($inputFileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                    if($row > 1
                      //2014-04-23 开启淘宝订单导入&& trim(iconv('GBK','utf-8',$data['20'])) != '淘宝'  //不导入淘宝订单13-08-19 避免药房网对淘宝订单多造或出错
                      && shouldAddOrder( trim($data['0'] ) )
                      && is_numeric(trim($data['0'] ) ) //只有订单号是数字的才导入
                      && shouldAddMallOrder( trim($data['21']) ) //
                     ) { //start from second line
                       // 去掉重复订单 TODO templately remove tmall order 2013-05-13

                       $sdata = array(
                           'sale_no' => trim($data['0']),

                           'customer_name' => trim(iconv('GBK','utf-8',$data['1'])),
                           //'alipay' => trim(iconv('GBK','utf-8',$data['2'])),
                           'total' => trim($data['3']),
                           'logifee' => trim($data['4']),
                           'sum_pay' => trim($data['3']),
                           'should_pay' => ( $data['3'] + $data['4'] - $data['5']),    //总金额+运费-红包 = 应付款
                           'real_pay' => ( $data['3'] + $data['4'] - $data['5']),  
                           //订单状态转换统一的
                           'order_status' => getOrderStatus ( trim(iconv('GBK','utf-8',$data['6'])) ),
                           'create_time' => strtotime( trim($data['7']) ),
                           'shipping_time' => strtotime(trim($data['8']) ),
                           'pay_method' => trim(iconv('GBK','utf-8',$data['9'])),
                           
                           
                           'logicompany' => trim(iconv('GBK','utf-8',$data['10'])), //exchange to id
                           'logicompany_id' => !empty($data['10']) ? getExpressId( trim(iconv('GBK','utf-8',$data['10'])) ) : '', // exchange to id
                           
                           'logino' => trim($data['11']),
                           'invoice_type' => trim(iconv('GBK','utf-8',$data['12'])),  
                           'invoice_title' => trim(iconv('GBK','utf-8',$data['13'])),
                           'invoice_content' => trim(iconv('GBK','utf-8',$data['14'])),
                           'customer_msg' => $this-> remove_alimsg( trim(iconv('GBK','utf-8',$data['15'])) ), //去掉支付宝交易号备注

                           //shipping address info
                           'shipping_name' => trim(iconv('GBK','utf-8',$data['16'])),
                           'address' => trim(iconv('GBK','utf-8',$data['17'])),
                           'city' => $this->get_municipality(trim(iconv('GBK','utf-8',$data['22'])) , iconv('GBK','utf-8',$data['23']) ), //直辖市要特别处理
                           'county' => $this->get_district( trim(iconv('GBK','utf-8',$data['22'])) ,trim(iconv('GBK','utf-8',$data['23'])), trim(iconv('GBK','utf-8',$data['24']))   ),  //城市
                           'province' => trim(iconv('GBK','utf-8',$data['22'])), //省份

                           'phone' => trim(iconv('GBK','utf-8',$data['18'])),
                           'mobile' => fixMobile(trim(iconv('GBK','utf-8',$data['19'])) ),
                           'order_source_id' => $this->get_order_source( trim(iconv('GBK','utf-8',$data['20'])) ), // 订单来源
                           'mall_no' => trim(iconv('GBK','utf-8',$data['21'])), //第三方订单号
                           'warehouse_id' => 1,
                           'user_id' => $_SESSION[C('USER_AUTH_KEY')],
                           'sum_number' => getSumNumber( trim($data['0']) ),

                       );
                       if(trim(iconv('GBK','utf-8',$data['20'])) == '当当')
                           $sdata['should_pay'] = $data['3'] + $data['4'] ; //如果是当当，则不减去红包，避免礼品卡支付为0 情况
                        //药房网的customer_id must get name with mobile and phone to got unique
                       $customer_id = getCustomerId($sdata['customer_name'],'',$sdata['mobile'],$sdata['phone'] ); 
                       $sdata['customer_id'] = $customer_id ;
                       $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata['phone'] );
                       $sdata['shipping_address_id'] = $shipping_address_id ;
                       $sale_id = $sale -> add($sdata);
                       //将sale_detail表中相应的sale_id 补全
                       $sale_detail ->where('sale_no ="'.$sdata['sale_no'].'"')->setField('sale_id',$sale_id);
                       $sale_no_data[$i] = $sdata['sale_no'];
                       $i++;
                       unset($sdata);
                    }
                    $row++;
                }
                fclose($handle);
                GiftAction::mass_add_gift($sale_no_data);
                SaleModel::auto_split_mass_order();
                $this->success("成功导入 ".$i." 条订单",false,5);
                }
            }
        }
    }

    //同步药房网订单，导入药房网订单后，将会把系统中淘宝订单号替换为药房网订单号；原始单号保留为淘宝订单号
    public function sync_yaofang()
    {
      if(($_FILES['upload']['name'] == '') ){
          $this->display();
          return;
      }
      

      $inputFileName = A('Import')->getCsv();
        $file_type = $_POST['file_type'];
        $jw_map = getPmap(1); //京卫匹配的产品列表 Out_number=> my_number

        $sale_detail = M('Sale_detail');
        $sale = M('Sale');
        $sdata = array(); // get line data from csv
        $i = 0; //统计有多少 条记录成功导入
       
       if(!strpos($inputFileName, 'order1') ) 
       {
          $this->error('请上传药房网订单文件，文件名为order1字样');
       }
          $row = 1;
          $sale_no_data = array(); //存入订单号
          if (($handle = fopen($inputFileName, "r")) !== FALSE) {
          while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
            $order_source = trim(iconv('GBK','utf-8',$data['20']));
            $mall_no = trim(iconv('GBK','utf-8',$data['21']));

            if($row > 1
              && trim($data['0']) != ""
              && $order_source == "淘宝" ) {
                //限制在淘宝来源的 订单，订单号等于药房网第三方订单号的，则是从淘宝上导入的订单
                $sale_tb_id = $sale->where('sale_no = "'.$mall_no.'" and order_source_id = 3')->getField('id');
                if(!$sale_tb_id)
                  continue;

               $sdata = array(
                   'sale_no' => trim($data['0']),
                   'mall_no' => $mall_no, //第三方订单号
                   'is_shipping_mall' => 0 //置平台未发货

               );

               $sale -> where( 'id = '.$sale_tb_id )->save($sdata);
               //将sale_detail表中相应的sale_no 替换，未取sale_tb_id
               $sale_detail ->where('sale_no ="'.$mall_no.'"')->setField('sale_no',$sdata['sale_no']);
               $i++;
               unset($sdata);
            }
            $row++;
        }
          fclose($handle);
          //TODO 是否要清除sale_id = 0 的sale_detail记录； 如果要清除，之前老的订单不能清除，需定义 一个节点。
          $sale_detail ->where('sale_id = 0 and create_time > '.strtotime("2013-08-10"))->delete();
          $this->success("成功同步 ".$i." 条订单",false,5);
          
        }
  
        
        unlink($inputFileName); //上传后删除文件
    }

     protected function merge_order(&$new_orders,$list,$value,$key){
      
        //如果地址及收货人相同，则合并订单,并且是同一平台下的
      //TODO 存在不同快递的情况，需要排除
          if( trim( $list[$key - 1]['shipping_name'] ) == trim($value['shipping_name'] ) 
              && trim( $list[$key - 1]['address'] )  == trim( $value['address'] )
              && ( $list[$key-1]['order_source_id'] == $value['order_source_id']  )
               ){

             if( is_array($new_orders[$key-1]) ){ //仅存在数组时，才合并
                $new_orders[$key - 1]['id'] .= ','.$value['id'];
                $new_orders[$key - 1]['sale_no'] .= ','.$value['sale_no'];
             }else{
                //不是数组，进入上一层数组,递归
                if($key-1 >0){
                   $this->merge_order($new_orders,$list,$value,$key-1);
                }
              } }else
          $new_orders[$key] = $value;

      return $new_orders;
  }

   public function get_order_source($value='')
   {
     $order_source_id = 0; 
     switch ($value) {
       case '京东':
         $order_source_id = 2;
         break;
      case '药房网':
         $order_source_id = 1;
         break;
      case '淘宝':
         $order_source_id = 3;
         break;
      case '当当':
         $order_source_id = 9;
         break;
       default:
         $order_source_id = 3;
         break;
     }
     return $order_source_id;
   }

  //如果内部产品编码不为0，则返回true,否则返回false
   private function check_pid_zero($sale_id=0)
   {
     $sale_details = M('Sale_detail')->where('sale_id ='.$sale_id )->field('id,product_id')->findAll();
     foreach ($sale_details as $key => $value) {
        if($value['product_id'] == 0 )
          return false;
        else 
          continue;
     }
     return true;
   }

   //默认不填快递公司情况下，如果运单号小于12或不为数字，则提示错误；其他情况根据快递公司规则处理
   private function check_logino($logino,$logicompany_id = 0){
    //如果不为空时，则进行判断
    if(!empty($logino)){
        if( $logicompany_id == 20 && (strlen($logino) != 12 && strlen($logino)!= 10 ) )  //yuan通 12
          $this->error("圆通运单号位数必须等于 12或10！",false,5);
        else if( $logicompany_id == 21 && strlen($logino) != 13 )  //韵达 13位
          $this->error("韵达运单号位数必须等于 13！",false,5);
        else if( $logicompany_id == 17 && strlen($logino) != 12 )  //中通 12
          $this->error("中通运单号位数必须等于 12！",false,5);
        else if( $logicompany_id == 18 && strlen($logino) != 12 )  //汇通快运 12
          $this->error("汇通快运 运单号位数必须等于 12！",false,5);
        else if( $logicompany_id == 27 && strlen($logino) != 13 )  //邮政国内小包 27
          $this->error("邮政国内小包运单号位数必须等于 13！",false,5);
        
        else if(!is_numeric($logino))
          $this->error('运单号只能为数字！'); //TODO 五环可能有问题，是字母加数字
      }
     

    }

  //必须按product_id排序，才能使用合并方法
  public function merge_order_detail(&$order_detail,$sale_detail){
        foreach ($sale_detail as $key => $value) {
            $this -> __merge_order_detail($order_detail,$sale_detail,$value,$key);
        } return $order_detail;
    }

  public  function __merge_order_detail(&$order_detail,$sale_detail,$value,$key){
       
            if($key == 0)
                $order_detail[0] = $value;
            else{
                if( $value['product_id'] != 0 && 
                  $value['product_id'] == $sale_detail[$key-1]['product_id']
                    ){
                    if(is_array($order_detail[$key-1])){
                       $order_detail[$key-1]['number'] += $value['number'];
                        $order_detail[$key-1]['total'] += $value['total']; 
                    }else{
                        $this->__merge_order_detail($order_detail,$sale_detail,$value,$key-1); }
                    
                }else
                   $order_detail[$key] = $value;
            }
        return $order_detail;
    }

    //根据sale_id　减去订单的库存
    public function update_sale_stock($sale_id='')
    {
       $sale =  M('Sale')->getById($sale_id);
       //如果订单状态不为已发货，则不处理库存
       if($order_status = $sale['order_status'] != 3 )
        return ;
      $detail_datas = M('Sale_detail')->where( 'sale_id = '. $sale_id)->findAll() ;
      $trans = A('Trans');
      foreach ($detail_datas as $detail_data) {
        if(getModelName($detail_data['product_id'],'Product','is_virtual' ) == 1 )
          continue; //虚拟物品不减库存
        $trans->updateStock($detail_data['product_id'], $detail_data['warehouse_id'], 'out', $detail_data['number'] );
      }
      
    }

    //去掉药房网传过来的支付宝交易号
    protected function remove_alimsg($msg){
        $k = preg_replace("/<br>(.*)+/" ,'',$msg);
        return $k;
    }


  //如果订单中产品库存不足，则返回提示
  public function check_stock($sale_id){
    /* 暂时不控制 2013-06-21
      $sale_details = M('Sale_detail')->where('sale_id ='.$sale_id)->field('product_id,number')->findAll();
      foreach ($sale_details as $value) {
        if(getModelName($value['product_id'],'Product','is_virtual') == 1  )
          continue; //虚拟物品，跳过处理
        $stock = getStock($value['product_id']);
        if($value['number'] > $stock)
          $this->error(getModelName($value['product_id'],'Product' )." 库存不足！",false,10);
      } */
  }
  //查询淘宝漏单情况。
    public function import_loudan()
    {
     if(($_FILES['upload']['name'] == '') ){
          $this->display();
          return;
      }
      if(empty($_POST['order_source_id']))
          $this->error("请选择订单来源");
 
      $inputFileName = A('Import')->getCsv();
      $row = 1 ;
      $loudan = array(); //漏单数组
      $line = "";
      if (($handle = fopen($inputFileName, "r")) !== FALSE) {
          while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
              if($row > 1  ){
                if($_POST['order_source_id'] != 5){
                    $rs = M('Sale')->where('mall_no ="'.trim($data['0']).'" and order_source_id='.$_POST['order_source_id'])->getField('id');
                    if(!$rs){ //漏单
                        $line .=trim($data['0'])."\n";
                    }
                    
                }else{ //德生堂订单，有合并的情况 
                  $unin_map['_string'] ='locate("' .trim($data['0']).'",mall_no) > 0 ';
                  $unin_map['order_source_id'] = 5 ;
                  $rs = M('Sale')->where($unin_map)->getField('id');
                  if(!$rs){ //漏单
                        $line .=trim($data['0'])."\n";
                }                 
              }
         }
         $row ++;
      }
    }
    $filename = "DYW_loudan".date('Ymd_His').'.csv'; //设置文件名 
    export_csv($filename,$line);
}

  //如果对应的城市是直辖市的，则返回对应省份作为城市。用以纠正京卫系统中直辖市的城市设置错误
  private function get_municipality($province,$city)
  {
    if($province == '上海市' || $province == '北京市' || $province == '天津市' || $province == '重庆市' )
      return $province;
    else
      return $city;
  }

  //纠正原来京卫系统中直辖市的区放在城市里的错误；如果是非直辖市，则返回对应的区或县
  private function get_district($province,$city,$county){
    if($province == '上海市' || $province == '北京市' || $province == '天津市' || $province == '重庆市' )
      return $city;
    else
      return $county;
  }

  //如果理论应付款大于实际 付款，则返回实际付款，以处理折价促销的订单
  private function get_should_pay($should_pay ,$real_pay)
  {
     $rpay = $real_pay > $should_pay ? $should_pay : $real_pay;
     return $rpay;
  }

  /**
  **发货短信通知
  *@mobile 手机号码
  *@logicompany 快递公司名称
  *@logino 运单号
  *@order_source 店铺ID
  **/
  public function shipping_notice($mobile,$logicompany,$logino,$order_source_id){
      $t =C('shipping_notice');
      $t = str_replace('logicompany', $logicompany, $t);
      $msg = str_replace('logi_no', $logino, $t);
      $order_source = S('order_source');

      $msg .="【".$order_source[$order_source_id]."】"; //短信带上签名
      A('OrderAPI')->sendMessages($mobile,$msg);
  }

  //人工拆单
  public function manual_split_order(){
     if(!empty($_REQUEST['id'])){
         SaleModel::split_order($_REQUEST['id'],0);//人工拆单,可以将原来非代售订单改为大眼窝订单
         $this->success("拆单成功!");
     }else
         $this->error("请选择需要拆单的订单号");  
  }


}
?>
